<script setup lang="ts">
  function tinymceScriptReady(): Promise<typeof import("tinymce").default> {
    if ((window as any).tinymce) {
      return Promise.resolve((window as any).tinymce);
    }
    if (!window["Tinymce_preloader"]) {
      window["Tinymce_preloader"] = new Promise<any>(resolve => {
        const scriptEl = document.createElement("script");
        scriptEl.integrity = "sha256-yFZrFbtKKJ5Q+buySYOf3fcUbtRMwXrQXAPqHMqNmRo=";
        // https://cdn.jsdmirror.com/npm/tinymce@6.8.5/tinymce.min.js  // 国内CDN，三方
        // https://jsd.onmicrosoft.cn/npm/tinymce@6.8.5/tinymce.min.js  // 国内CDN，三方
        // https://testingcf.jsdelivr.net/npm/tinymce@6.8.5/tinymce.min.js  可用性高
        // https://gcore.jsdelivr.net/npm/tinymce@6.8.5/tinymce.min.js  可用性高
        // https://quantil.jsdelivr.net/npm/tinymce@6.8.5/tinymce.min.js  可用性一般
        // https://fastly.jsdelivr.net/npm/tinymce@6.8.5/tinymce.min.js  可用性一般
        scriptEl.src = "https://gcore.jsdelivr.net/npm/tinymce@6.8.5/tinymce.min.js";
        // scriptEl.src = "https://gcore.jsdelivr.net/npm/tinymce@5.10.9/tinymce.min.js";
        scriptEl.crossOrigin = "anonymous";
        scriptEl.charset = "utf-8";
        scriptEl.async = true;
        scriptEl.defer = true;
        scriptEl.type = "application/javascript";
        scriptEl.onload = () => {
          resolve((window as any).tinymce);
          document.head.removeChild(scriptEl);
          window["Tinymce_preloader"] = null;
          delete window["Tinymce_preloader"];
        };
        document.head.appendChild(scriptEl);
      });
    }
    return window["Tinymce_preloader"];
  }
  // 不提供第一个参数是，默认的prop 名称为modelValue
  const modelValue = defineModel<string>({
    type: String,
    default: "",
  });

  const vm = getCurrentInstance();
  const tinymceEditor = ref<import("tinymce").Editor>(null);

  onMounted(async () => {
    // vm.vnode.el
    const tinymce = await tinymceScriptReady();
    // cdn => jsdeliver

    const tinymceInstances = await tinymce.init({
      target: vm.vnode.el as any,
      // selector: `#${this.id}`,
      // skin: "silver",
      fullpage_default_doctype: "<!DOCTYPE html>",
      fullpage_default_encoding: "UTF-8",
      fullpage_default_font_family: "sans-serif",
      // base_url: "https://gcore.jsdelivr.net/npm/tinymce@6.8.5/",
      // urlconverter_callback: this.UrlConverterCallback, // URL 转换规则
      // paste_preprocess: this.PastePreProcess, // 在粘贴的内容被插入到编辑器之前对其进行修改（也相当于自建过滤器）。
      // paste_postprocess: this.PastePostProcess, // 在粘贴的内容被解析DOM结构，但在被插入到编辑器之前，对其进行修改。
      // document_base_url: process.env.VUE_APP_APIBASEURL,
      // valid_elements:"@[href|target|align|src|colspan|rowspan|style]",
      convert_urls: false,
      relative_urls: false,
      remove_script_host: false,

      min_height: 500,
      width: "100%",
      paste_data_images: true, // 拖入、粘贴图片的处理
      paste_webkit_styles: "all", // 不过滤style 中的内容
      branding: false, // 隐藏右下角信息
      menubar: false,
      resize: false, // 禁止调整大小
      draggable_modal: true, // 可以拖动弹窗
      contextmenu_never_use_native: true, // 在编辑器中屏蔽浏览器本身的右键菜单
      language: "zh_CN",
      // visualblocks_default_state: true,
      // language_url: "https://gcore.jsdelivr.net/npm/tinymce-i18n@19.9.17/langs5/zh_CN.js",
      language_url: "https://gcore.jsdelivr.net/npm/tinymce-i18n@24.12.30/langs5/zh_CN.js",
      // skin_url: "https://gcore.jsdelivr.net/npm/tinymce@6.8.5/skins/ui/oxide",
      // icons_url: "https://gcore.jsdelivr.net/npm/tinymce@6.8.5/icons/default/icons.min.js", // load icon pack
      skin: "oxide",
      // icons: "small",
      content_css: [
        "https://gcore.jsdelivr.net/npm/tinymce@6.8.5/skins/content/default/content.min.css",
        // "https://res.wx.qq.com/mpres/zh_CN/htmledition/comm_htmledition/style/widget/ueditor_new/themes/iframe49d030.css"
        "/css/weixin-editor-iframe.css",
      ],
      content_css_cors: true, // 自动添加 crossorigin="anonymous" 属性
      // toolbar_drawer: "sliding",
      plugins: "preview link emoticons image lists advlist visualblocks media template autolink wordcount quickbars table",
      // print fullpage  importcss searchreplace  directionality code visualchars codesample table charmap
      // pagebreak nonbreaking anchor toc insertdatetime imagetools textpattern noneditable help autosave save
      toolbar: [
        "visualblocks preview | undo redo | fontsizeselect | blockquote hr | removeformat | link emoticons table",
        "bold italic underline strikethrough forecolor backcolor | outdent indent | alignleft aligncenter alignright alignjustify | numlist bullist",
        "bdImageManage media template",
      ],
      quickbars_insert_toolbar: false,
      quickbars_selection_toolbar: "bold italic | quicklink blockquote bdImageManage",
      // theme_url:
      //   "https://gcore.jsdelivr.net/npm/tinymce@6.8.5/themes/silver/theme.js",
      // external_plugins: {
      //   wordcount:
      //     "https://gcore.jsdelivr.net/npm/tinymce@6.8.5/plugins/wordcount/plugin.min.js"
      // }, // 外部插件
      templates: [
        {
          title: "New Table",
          description: "creates a new table",
          content:
            '<div class="mceTmpl"><table width="98%"  border="0" cellspacing="0" cellpadding="0"><tr><th scope="col"> </th><th scope="col"> </th></tr><tr><td> </td><td> </td></tr></table></div>',
        },
        {
          title: "Starting my story",
          description: "A cure for writers block",
          content: "Once upon a time...",
        },
        {
          title: "New list with dates",
          description: "New List with dates",
          content:
            '<div class="mceTmpl"><span class="cdate">cdate</span><br /><span class="mdate">mdate</span><h2>My List</h2><ul><li></li><li></li></ul></div>',
        },
      ],
      setup: editorSetup,
    });

    tinymceEditor.value = tinymceInstances[0];

    tinymceEditor.value.setContent(modelValue.value);
  });

  onBeforeUnmount(() => {
    tinymceEditor.value?.destroy(true);
  });

  function editorSetup(editor: import("tinymce").Editor) {
    // 在工具栏上添加自定义图片选择器按钮
    editor.ui.registry.addButton("bdImageManage", {
      icon: "image", // the 'bold' icon  created from 'bold.svg'
      onAction: () => {
        debugger;
        // this.FileManageDialog.Show = true;
      },
    });

    // 绑定内容变化事件
    //  editor.on("input change undo redo execCommand KeyUp", () => {
    //       this.$emit("change", editor.getContent());
    //     });
    editor.on("change", () => {
      modelValue.value = editor.getContent();
    });
  }
</script>

<template>
  <textarea ></textarea>
</template>

<style lang="scss" scoped></style>
